<template>
	<div class="brandList">
		<el-card shadow="hover">
			<div class="brand-list mb15">
				<el-form ref="formDataRef" :inline="true" :model="state.formData" label-width="80px" class="demo-form-inline">
					<el-row>
						<el-col :span="24" style="text">
							<el-form-item>
								<div style="padding-left: 20px">
									<el-button type="success" @click="setDetailId(0)">新增品牌</el-button>
								</div>
							</el-form-item>
						</el-col>
						<el-col :span="5">
							<el-form-item label="关键词:" prop="keyWord" style="width: 100%">
								<el-input maxlength="200" v-model="state.formData.keyWord" placeholder="关键词" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="5">
							<el-form-item label="品牌ID" prop="brandId" style="width: 100%">
								<el-input maxlength="200" v-model.number="state.formData.brandId" placeholder="商品ID" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="5">
							<el-form-item label="分类" prop="classification" style="width: 100%">
								<CateSelector v-model="state.formData.classification" />
							</el-form-item>
						</el-col>
						<el-col :span="5">
							<el-form-item label="新增时间" prop="time" style="width: 100%">
								<el-date-picker
									style="width: 100%"
									value-format="YYYY-MM-DD"
									v-model="state.formData.time"
									type="date"
									placeholder="选择日期"
								></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :span="4">
							<div style="padding-left: 10px">
								<el-button type="primary" @click="searchFun">搜索</el-button>
								<el-button @click="resetForm">重置</el-button>
							</div>
						</el-col>
					</el-row>
				</el-form>
			</div>
			<el-table v-loading="state.loading" :data="state.tableData" style="width: 100%">
				<el-table-column prop="number" width="80px" label="序号"></el-table-column>
				<el-table-column prop="brandId" label="品牌ID"></el-table-column>
				<el-table-column prop="brandName" label="品牌名称"></el-table-column>
				<el-table-column prop="brandLogo" width="100px" label="品牌logo">
					<template #default="scope">
						<el-image lazy :src="scope.row.brandLogo" :preview-src-list="state.srcList" :initial-index="scope.$index" preview-teleported></el-image>
					</template>
				</el-table-column>
				<el-table-column label="是否启用">
					<template #default="scope">
						<el-switch v-model="scope.row.isEnabled" @change="() => editItem(scope.row)" />
					</template>
				</el-table-column>
				<el-table-column prop="numberOfCorrespondingProducts" label="对应商品数"></el-table-column>
				<el-table-column label="是否显示在页尾">
					<template #default="scope">
						<el-switch v-model="scope.row.isShowAtEndOfPage" @change="() => editItem(scope.row)" />
					</template>
				</el-table-column>
				<el-table-column label="排序">
					<template #default="scope">
						<el-input-number
							:step="1"
							:controls="false"
							v-model="scope.row.sort"
							:min="0"
							:max="999999"
							controls-position="right"
							style="width: 100px"
							@blur="() => editItem(scope.row)"
						/>
					</template>
				</el-table-column>
				<el-table-column label="编辑" width="120px">
					<template #default="scope">
						<el-button text :loading="state.deleteLoading" type="primary" @click="setDetailId(scope.row.id)">编辑</el-button>
						<el-button text :loading="state.deleteLoading" type="danger" @click="beforeDelete(scope.row)">禁用</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
		<el-dialog v-model="state.dialogVisible" :title="state.dialoagTitle" destroy-on-close width="80%">
			<BrandDetail ref="brandDetailRef" v-model:brandId="state.detailId" @reloadList="searchFun()" @closeDetailDialog="closeDetailDialog" />
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="closeDialog">取消</el-button>
					<el-button type="primary" @click="submit">保存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<script setup name="BrandList">
import 'dayjs/locale/zh-cn';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useBrandApi } from '/@/api/brand';
import BrandDetail from './BrandDetail.vue';
import CateSelector from '/@/components/common/CateSelector.vue';

const { delBrandById, editBrand, getBrandList } = useBrandApi();
const formDataRef = ref();
const brandDetailRef = ref();
const state = reactive({
	dialoagTitle: '编辑品牌',
	dialogVisible: false,
	formData: {
		keyWord: '',
		brandId: '',
		classification: 0,
		time: null,
	},
	tableData: [],
	srcList: [],
	loading: false,
	deleteLoading: false,
	page: {
		pageSize: 10,
		current: 1,
		total: 0,
	},
	detailId: -1,
});

async function init() {
	getList();
}

function searchFun() {
	if (state.loading) {
		return;
	}
	state.page = {
		pageSize: state.page.pageSize,
		current: 1,
		total: state.page.total,
	};
	getList();
}
function resetForm() {
	formDataRef.value.resetFields();
}

async function getList() {
	if (state.loading) {
		return;
	}
	state.loading = true;
	console.log('0-0----', state.formData);
	try {
		let params = {
			current: state.page.current,
			pageSize: state.page.pageSize,
			name: state.formData.keyWord ? state.formData.keyWord : null,
			status: 1, // 如果是null，表示查所有，是否展示 0->禁用；1->启用
			createDate: state.formData.time,
			id: state.formData.brandId ? state.formData.brandId : null,
			categoryId: state.formData.classification ? state.formData.classification : null,
			// type:"jpg" // 图片类型
		};
		console.log('0-0----', params);
		let res = await getBrandList(params);
		if (res.code !== 200) {
			state.loading = false;
			// ElMessage({
			//     type: "error",
			//     message: res.data.msg,
			// });
			return;
		}
		state.loading = false;
		state.page = {
			pageSize: res.data.pageSize,
			current: res.data.current,
			total: res.data.total,
		};

		let tempList = res.data.data.map((item, index) => {
			return {
				id: item.id,
				number: (res.data.current - 1) * 10 + index + 1,
				brandId: item.id,
				brandName: item.name,
				brandLogo: item.logo,
				isEnabled: item.isUse === 1 ? true : false, // 是否展示 0->不展示；1->展示
				isShowAtEndOfPage: item.showStatus === 1 ? true : false,
				numberOfCorrespondingProducts: item.productCount,
				sort: item.sort,
			};
		});

		state.tableData = tempList;

		setSrcList(tempList);
	} catch (error) {
		state.loading = false;
		ElMessage({
			type: 'error',
			message: '获取品牌列表失败',
		});
	}
}

async function editItem(item) {
	if (state.loading) {
		return;
	}
	state.loading = true;
	console.log(item);

	try {
		let params = {
			id: item.id,
			name: item.brandName,
			isUse: item.isEnabled ? 1 : 0,
			showStatus: item.isShowAtEndOfPage ? 1 : 0,
			sort: item.sort,
		};
		let res = await editBrand(params);
		if (res.code !== 200) {
			state.loading = false;
			// ElMessage({
			//     type: "error",
			//     message: res.data.msg,
			// });
			return;
		}
		ElMessage({
			type: 'success',
			message: '保存成功！',
		});
		state.loading = false;
		getList();
	} catch (error) {
		state.loading = false;
		ElMessage({
			type: 'error',
			message: '修改失败',
		});
	}
}

function setSrcList(list) {
	state.srcList = list.map((item) => {
		return item.brandLogo ? item.brandLogo : '';
	});
}

async function deleteFun(id) {
	// console.log(id);
	if (state.deleteLoading) {
		return;
	}
	state.deleteLoading = true;
	let params = id;
	try {
		let res = await delBrandById(params);
		if (res.code !== 200) {
			state.deleteLoading = false;
			// ElMessage({
			//     type: "error",
			//     message: res.data.msg,
			// });
			return;
		}
		ElMessage({
			type: 'success',
			message: '禁用成功！',
		});
		state.deleteLoading = false;
		getList();
	} catch (error) {
		state.deleteLoading = false;
		ElMessage({
			type: 'error',
			message: '禁用失败',
		});
	}
}

function beforeDelete(row) {
	ElMessageBox.confirm(`确认禁用品牌：${row.brandName}?`, '禁用品牌', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			deleteFun(row.id);
		})
		.catch(() => {});
}

// 设置详情的id
function setDetailId(id) {
	state.dialogVisible = true;
	state.detailId = id;
}

const closeDetailDialog = () => {
	state.dialogVisible = false;
};

const submit = () => {
	brandDetailRef.value.submitForm();
};

const closeDialog = () => {
	brandDetailRef.value.cancel();
	closeDetailDialog();
};

onMounted(() => {
	init();
});
</script>
<style lang="scss" scoped></style>
